package com.shu.auth.common;

import com.shu.auth.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常解析
 */
@Component
@Slf4j
public class SpringExceptinoResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url=request.getRequestURL().toString();
        ModelAndView mv=null;
        String defaultMsg="系统异常";
        //.json .page
        //要求项目中，所有请求json数据都使用.json结尾
        if (url.endsWith(".json")){
            if (e instanceof BaseException){
                JsonData result =JsonData.fial(e.getMessage());
                mv=new ModelAndView("jsonView",result.toMap());

            }else {
                log.error("unknow json exception,url:{}",url,e);
                JsonData result =JsonData.fial(defaultMsg);
                mv=new ModelAndView("jsonView",result.toMap());
            }
        }else if (url.endsWith(".page")){//要求项目中，所有请求jsp都使用.page结尾
            log.error("unknow page exception,url:{}",url,e);
            JsonData result = JsonData.fial(defaultMsg);
            mv=new ModelAndView("exception",result.toMap());
        }else {
            log.error("unknow exception,url:{}",url,e);
            JsonData result = JsonData.fial(defaultMsg);
            mv=new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }
}
